<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>冒泡排序</title>
</head>

<body>
  <script>
    /* 
     * 冒泡排序的思想: 
     *  让数组中的当前项和后一项进行比较, 如果当前项比后一项大, 则两项交换位置(让大的靠后)即可
    */
    let ary = [12, 8, 24, 16, 1];

    /* 
     * bubble: 实现冒泡排序
     *  @params
     *    ary [array] 需要排序的数组
     *  @return
     *    [array] 排序后的新数组
     * by chenjing on 2021/01/23
    */
    function bubble(ary) {
      let temp = null;
      for (let i = 0; i < ary.length - 1; i++) {
        for (let j = 0; j < ary.length - 1 - i; j++) {
          if(ary[j] > ary[j + 1]) {
            temp = ary[j];
            ary[j] = ary[j + 1];
            ary[j + 1] = temp;
          }
        }
      }
      return ary;
    }
    console.log(bubble(ary));
  </script>
</body>

</html>